//# sourceURL=http://umap.jsmuhang.com/UI/PC/Layer/UavFlight
(function () {

    Namespace.Class("Umap.UI.PC.Layer", UavFlight);
    var Interface = Namespace.Import("Umap.Tool.Interface");
    var Ajax = Namespace.Import("Umap.Tool.Ajax");

    function UavFlight(option) {

        var _this = this;

        _this.isLoaded = false;
        _this.isOpened = false;
        _this.positions = [];

        option && _this._init(option);

        var viewer = umapEarthJs.earthViewer;
        var camera = viewer.camera;

        _this.load = function (onLoad) {

            if (!_this.isLoaded) {

                _this.dataURL = _this.videoBaseURL + _this.folder + "/" + _this.file + ".json";
                _this.videoURL = _this.videoBaseURL + _this.folder + "/" + _this.file + ".mp4";

                Ajax({
                    type     : "GET",
                    dataType : "json",
                    url      : _this.dataURL,
                    success  : function (json) {
                        if (json.code == 1) {

                            _this.positions = json.data.positions;

                            _this.position = {
                                start : _this.positions[0],
                                stop  : _this.positions[_this.positions.length - 1]
                            };

                            _this.isLoaded = true;
                            _this.init();
                            onLoad && onLoad(_this);
                        }
                    }
                });

            } else {
                onLoad && onLoad();
            }
        };

        _this.init = function () {

            _this.startTime = uEarth.JulianDate.fromDate(new Date(_this.positions[0].time));
            _this.stopTime = uEarth.JulianDate.fromDate(new Date(_this.positions[_this.positions.length - 1].time));
            _this.property = new uEarth.SampledPositionProperty();

            $.each(_this.positions, function (i, position) {

                if (i == 0 || i % 10 == 0 || i == _this.positions.length - 1) {
                    var c3p = uEarth.Cartesian3.fromDegrees(Number(position.longitude), Number(position.latitude), 100);

                    if (i == _this.positions.length - 1) {
                        _this.property.addSample(_this.stopTime, c3p);
                    } else {
                        _this.property.addSample(uEarth.JulianDate.fromDate(new Date(position.time)), c3p);
                    }
                }
            });

            _this.entity = viewer.entities.add({
                availability : new uEarth.TimeIntervalCollection([new uEarth.TimeInterval({
                    start : _this.startTime,
                    stop  : _this.stopTime
                })]),
                position     : _this.property,
                orientation  : new uEarth.VelocityOrientationProperty(_this.property),
                path         : {
                    resolution : 1,
                    material   : _this.isMain ? uEarth.Color.YELLOW.withAlpha(0.5) : uEarth.Color.AQUA.withAlpha(0.5),
                    width      : _this.isMain ? 5 : 5
                }
            });

            if (!_this.isMain) {
                _this.marker = viewer.entities.add({
                    position  : uEarth.Cartesian3.fromDegrees(Number(_this.positions[0].longitude), Number(_this.positions[0].latitude), 10),
                    billboard : new uEarth.BillboardGraphics({
                        image                    : "./img/icon/iconLBS_02.png",
                        pixelOffset              : new uEarth.Cartesian2(0, -10),
                        heightReference          : uEarth.HeightReference.RELATIVE_TO_GROUND,//地形之上
                        distanceDisplayCondition : Number.POSITIVE_INFINITY
                    })
                });

                _this.marker.click = function () {
                    if (uiApp.uavLayerPanel.uavLayer.currentFlight != _this) {
                        uiApp.uavLayerPanel.uavLayer.currentFlight.close();
                        uiApp.uavLayerPanel.uavLayer.currentFlight = _this;
                        uiApp.uavLayerPanel.uavLayer.currentFlight.open(function () {
                            uiApp.uavLayerPanel.uavLayer.video.url = _this.videoUrl;
                            uiApp.uavLayerPanel.uavLayer.video.play();
                        });
                    }
                };
            }
        };

        _this.open = function (onOpen) {

            if (_this.isLoaded) {
                if (!_this.isOpened) {

                    // uiApp.uavLayerPanel.checkboxs.child[0].unCheck();

                    viewer.clock.startTime = _this.startTime.clone();
                    viewer.clock.stopTime = _this.startTime.clone();
                    // viewer.clock.clockRange = uEarth.ClockRange.LOOP_STOP; //Loop at the end
                    viewer.clock.shouldAnimate = false;
                    viewer.clock.currentTime = viewer.clock.startTime.clone();
                    _this.entity.show = true;

                    _this.entity.path.material = uEarth.Color.RED.withAlpha(0.5);
                    _this.entity.billboard = new uEarth.BillboardGraphics({
                        image           : "./img/icon/iconLBS_00.png",
                        pixelOffset     : new uEarth.Cartesian2(0, -10),
                        heightReference : uEarth.HeightReference.RELATIVE_TO_GROUND//地形之上
                    });

                    // _this.fly();

                    _this.isOpened = true;
                    onOpen && onOpen(_this);

                    // _this.fly();

                } else {
                    onOpen && onOpen();
                }

            } else {
                _this.load(function () {
                    _this.open(onOpen);
                });
            }
        };

        _this.fly = function () {

            viewer.flyTo(_this.entity, {
                offset : new uEarth.HeadingPitchRange(0, -30, uEarth.Cartographic.fromCartesian(camera.position).height)
            });

            // !uiApp.uavLayerPanel.uavLayer.video.isFullScreen && camera.flyTo({
            //     destination: uEarth.Cartesian3.fromDegrees(Number(_this.positions[0].longitude), Number(_this.positions[0].latitude), uEarth.Cartographic.fromCartesian(camera.position).height),
            //     orientation: {
            //         heading: uEarth.Math.toRadians(0),
            //         pitch  : uEarth.Math.toRadians(-35.0),
            //         roll   : 0.0
            //     }
            // });

            // !uiApp.uavLayerPanel.uavLayer.video.isFullScreen && viewer.zoomTo(_this.entity, new uEarth.HeadingPitchRange(0, -10, uEarth.Cartographic.fromCartesian(camera.position).height));
        };

        _this.gotoPosition = function (position) {
            viewer.clock.currentTime = uEarth.JulianDate.fromDate(new Date(_class.getNearestPosition(position, _this.positions).time));
            viewer.clock.shouldAnimate = false;
        };

        _this.close = function (onClose) {

            if (_this.isLoaded && _this.isOpened) {
                _this.entity.path.material = _this.isMain ? uEarth.Color.YELLOW.withAlpha(0.5) : uEarth.Color.AQUA.withAlpha(0.5);
                _this.entity.billboard = null;
                viewer.clock.currentTime = viewer.clock.startTime.clone();
            }

            _this.isOpened = false;
            onClose && onClose();

        };

        _this.clear = function (onClear) {

            _this.entity.show = false;
            _this.isOpened = false;
            onClear && onClear();

        };

        _this.toggle = function (onToggle) {
            if (_this.isOpened) {
                _this.close(onToggle);
            } else {
                _this.open(onToggle);
            }

        };

        _this.onInit && _this.onInit(_this);

    }


    var _class = UavFlight;
    Interface._initAble.call(_class);

    _class.getNearestPosition = function (targetPosition, positions) {

        var nearestDistance;
        var resultPosition;

        $.each(positions, function (i, position) {

            var distance = uEarth.Cartesian2.distance(
                new uEarth.Cartesian2(position.longitude, position.latitude),
                new uEarth.Cartesian2(targetPosition.longitude, targetPosition.latitude)
            );

            if (nearestDistance) {
                if (nearestDistance > distance) {
                    nearestDistance = distance;
                    resultPosition = positions[i];
                }
            } else {
                nearestDistance = distance;
                resultPosition = positions[i];
            }

        });

        return resultPosition;

    };

})();